package com.buka.service.impl;

import com.alibaba.fastjson.JSON;
import com.buka.dao.OrderDao;
import com.buka.entity.Order;
import com.buka.service.OrderTccAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class OrderTccActionImpl implements OrderTccAction {

    @Resource
    private OrderDao orderDao;

    @Override
    public boolean prepareCreateOrder(BusinessActionContext ctx,Order order) {
        // Try 阶段：创建订单（状态为创建中）
        int rows = orderDao.insert(order);

        return rows > 0;
    }

    @Override
    public boolean confirm(BusinessActionContext ctx) {
        // Confirm 阶段：确认订单（幂等设计）
        String orderStr = ctx.getActionContext("order").toString();
        Order order = JSON.parseObject(orderStr, Order.class);
        order.setStatus(1);
        int rows = orderDao.updateById(order);
        if(rows <1 ){
            throw new RuntimeException();
        }

        return rows>0;
    }

    @Override
    public boolean cancel(BusinessActionContext ctx) {
        String orderStr = ctx.getActionContext("order").toString();
        Order order = JSON.parseObject(orderStr, Order.class);
        order.setStatus(2);
        // Cancel 阶段：取消订单（幂等设计）
        int rows = orderDao.updateById(order);
        return rows > 0;
    }
}